package own.stu.jobgib.playown.vediodown.common;

import lombok.Data;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * url工具类
 */
public class UrlUtil {

    @Data
    public static class UrlEntity {
        /**
         * 基础url
         */
        public String baseUrl;
        /**
         * url参数
         */
        public Map<String, String> params;
    }

    public static String compose(UrlEntity entity) {
        String url = entity.getBaseUrl();
        Map<String, String> params = entity.getParams();
        if (params == null || params.size() == 0) {
            return url;
        }
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> en = iterator.next();
            sb.append(en.getKey());
            sb.append("=");
            sb.append(en.getValue());
            if (iterator.hasNext()) {
                sb.append("&");
            }
        }
        return sb.toString();
    }

    /**
     * 解析url
     *
     * @param url
     * @return
     */
    public static UrlEntity parse(String url) {
        UrlEntity entity = new UrlEntity();
        if (url == null) {
            return entity;
        }
        url = url.trim();
        if (url.equals("")) {
            return entity;
        }
        String[] urlParts = url.split("\\?");
        entity.baseUrl = urlParts[0];
        //没有参数
        if (urlParts.length == 1) {
            return entity;
        }
        //有参数
        String[] params = urlParts[1].split("&");
        entity.params = new HashMap<>();
        for (String param : params) {
            String[] keyValue = param.split("=");
            if (keyValue.length > 1) {
                entity.params.put(keyValue[0], keyValue[1]);
            }
        }

        return entity;
    }

    /**
     * 获取url指定参数值
     *
     * @param url
     * @param key 参数名
     * @return
     */
    public static String getParamsByKey(String url, String key) {
        UrlEntity entity = parse(url);
        return entity.params.get(key);
    }

}

